package com.bhs.sansonglogistics.ui.adapter;

import static com.luck.picture.lib.thread.PictureThreadUtils.runOnUiThread;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.GlideEngine;
import com.bhs.sansonglogistics.bean.ImageReturn;
import com.bhs.sansonglogistics.bean.PictureBean;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.dialog.MyClickListener2;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.enterprise.EnterpriseCertificationActivity;
import com.bhs.sansonglogistics.utils.DateUtils;
import com.bhs.sansonglogistics.utils.FileSizeUtil;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;

import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.interfaces.OnVideoThumbnailEventListener;
import com.luck.picture.lib.utils.PictureFileUtils;
import com.xiaoguang.widget.videocompress.core.VideoCompress;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Response;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class PictureSelectAdapter extends BaseMultiItemQuickAdapter<PictureBean, BaseViewHolder> implements NetCallBack {
    //图片选择的最大数量
    private int maxSelectNum;
    private int maxVideoSelectNum = 1;
    private int index = 0;
    private BaseActivity activity;
    public ArrayList<LocalMedia> localMedia = new ArrayList<>();
    private int selectMimeType = SelectMimeType.TYPE_IMAGE;
    private String destPath;
    private boolean isVideo;

    public PictureSelectAdapter(int maxSelectNum, BaseActivity activity) {
        super(new ArrayList<>());
        this.maxSelectNum = maxSelectNum;
        this.activity = activity;
        mData.add(new PictureBean(PictureBean.add));
        addItemType(PictureBean.picture, R.layout.item_picture);
        addItemType(PictureBean.add, R.layout.layout_add_picture);
    }

    public PictureSelectAdapter(BaseActivity activity) {
        super(new ArrayList<>());
        this.maxSelectNum = 2;
        this.activity = activity;
        mData.add(new PictureBean(PictureBean.add));
        addItemType(PictureBean.picture, R.layout.item_video);
        addItemType(PictureBean.add, R.layout.item_video_add);
    }


    @Override
    protected void convert(@NonNull BaseViewHolder helper, PictureBean item) {
        if (helper.getItemViewType() == PictureBean.picture) {
            helper.setGone(R.id.iv_video, !TextUtils.isEmpty(item.getVideoThumbnailPath()));
            if (TextUtils.isEmpty(item.getVideoThumbnailPath())) {
                Glide.with(mContext).load(item.getPath()).into((ImageView) helper.getView(R.id.iv_picture));
            } else {
                Glide.with(mContext).load(item.getVideoThumbnailPath()).into((ImageView) helper.getView(R.id.iv_picture));
            }
            helper.getView(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    delete(helper.getLayoutPosition());
                }
            });
            helper.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    preview(helper.getLayoutPosition());
                }
            });

        } else {
            helper.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //报黄是因为屏幕方向锁定了
                    PictureSelector.create(mContext)
                            .openGallery(selectMimeType)
                            .setMaxSelectNum(maxSelectNum)
                            .setMaxVideoSelectNum(maxVideoSelectNum)
                            .setRecordVideoMaxSecond(30)
                            .setFilterVideoMaxSecond(31)
                            .setVideoThumbnailListener(new MeOnVideoThumbnailEventListener())
                            .isWithSelectVideoImage(false)
                            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                            .setImageEngine(GlideEngine.createGlideEngine())
                            .setSelectedData(localMedia)
                            .forResult(new OnResultCallbackListener<LocalMedia>() {
                                @SuppressLint("NotifyDataSetChanged")
                                @Override
                                public void onResult(ArrayList<LocalMedia> result) {
                                    uploadPictures(result);
                                }

                                @Override
                                public void onCancel() {

                                }
                            });
                }
            });
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    public void uploadPictures(ArrayList<LocalMedia> result) {
        localMedia = result;
        for (LocalMedia localMedia : result) {
            boolean isHas = false;
            for (PictureBean mDatum : mData) {
                if (mDatum.getItemType() == PictureBean.add) {
                    mData.remove(mDatum);
                }
                if (TextUtils.isEmpty(localMedia.getRealPath()) ||
                        localMedia.getRealPath().equals(mDatum.getPath())) {
                    isHas = true;
                }
            }
            if (isHas) {
                continue;
            }
            mData.add(new PictureBean(1, localMedia.getRealPath(), localMedia.getVideoThumbnailPath()));
        }

        //是否还需要显示添加图标
        if (TextUtils.isEmpty(mData.get(0).getVideoThumbnailPath())) {
            if (result.size() < maxSelectNum) {
                mData.add(new PictureBean(2));
            }
        } else {
            if (result.size() < maxVideoSelectNum) {
                mData.add(new PictureBean(2));
            }
        }

        notifyDataSetChanged();
        activity.loadingPopupShow("正在处理");
        index = 0;
        imageUpload();
    }


    private void preview(int position) {

        PictureSelector.create(mContext)
                .openPreview()
                .setImageEngine(GlideEngine.createGlideEngine())
                .isVideoPauseResumePlay(true)
                .setExternalPreviewEventListener(new OnExternalPreviewEventListener() {
                    @Override
                    public void onPreviewDelete(int position) {
                        delete(position);
                    }

                    @Override
                    public boolean onLongPressDownload(Context context, LocalMedia media) {
                        return true;
                    }

                }).startActivityPreview(position, true, localMedia);

    }


    //文件上传
    private void imageUpload() {
        if (index >= mData.size()) {
            if (!isVideo) {
                activity.loadingPopupDismiss();
            }
            if (listener != null) {
                listener.onClick("1", "");
            }
            return;
        }
        if (mData.get(index).getNetworkPath() == null && mData.get(index).getPath() != null) {
            String path = mData.get(index).getPath();
            File file = new File(path);
            LogUtils.d(path);
            if (!path.endsWith(".mp4")) {
                //图片压缩
                photoCompression(file);
            } else {
                //视频压缩
                videoCompression(file);
            }
        } else {
            index++;
            imageUpload();
        }
    }

    private void videoCompression(File file) {
        LogUtils.d("视频开始压缩" + FileSizeUtil.getAutoFileOrFilesSize(file.getPath()));
        String fileName = System.currentTimeMillis() + ".mp4";
        destPath = activity.getExternalCacheDir().getPath() + "/" + fileName;
        LogUtils.d(DateUtils.getTime2(System.currentTimeMillis()) + "");

        // VideoCompress.compressVideoHigh   高质量压缩
// VideoCompress.compressVideoMedium 中质量压缩
// VideoCompress.compressVideoLow    低质量压缩
// inputPath  输入视频地址
// outputPath 输出视频地址
        VideoCompress.compressVideoLow(file.getPath(), destPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess() {
                // Finish successfully
                LogUtils.d("视频压缩完成" + FileSizeUtil.getAutoFileOrFilesSize(destPath));
                LogUtils.d(DateUtils.getTime2(System.currentTimeMillis()) + "");
                mData.get(0).setCompressedPath(destPath);
                activity.loadingPopupDismiss();
                if (listener != null) {
                    listener.onClick("1", "");
                }
            }

            @Override
            public void onFail() {
                // Failed
            }

            @Override
            public void onProgress(float percent) {
                // Progress 进度
            }
        });

    }

    private void photoCompression(File file) {
        Luban.with(activity)
                .load(file)
                .ignoreBy(100)
                .setTargetDir(activity.getExternalCacheDir().getPath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        MyUtils.fileUpload(activity, file, PictureSelectAdapter.this, 0);
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                    }
                }).launch();
    }


    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        ImageReturn dataBean = new Gson().fromJson(json, ImageReturn.class);
        if (dataBean.isStatus()) {
            mData.get(index).setNetworkPath(dataBean.getData().getSrc());
            if (!TextUtils.isEmpty(dataBean.getData().getTitle())) {
                mData.get(index).setCover(dataBean.getData().getTitle());
            }
            index++;
            imageUpload();
        } else {
            ToastUtil.show(dataBean.getMsg());
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    @SuppressLint("NotifyDataSetChanged")
    public void delete(int position) {
        localMedia.remove(position);
        mData.remove(position);
        if (mData.size() > 0 && mData.get(mData.size() - 1).getItemType() == 1) {
            mData.add(new PictureBean(2));
        }
        if (mData.size() == 0) {
            mData.add(new PictureBean(2));
        }
        notifyDataSetChanged();
        if (listener != null) {
            listener.onClick("", "");
        }
    }

    public String getImages() {
        StringBuilder images = new StringBuilder();
        for (PictureBean mDatum : mData) {
            if (mDatum.getItemType() == 1) {
                images.append(mDatum.getNetworkPath()).append("||");
            }
        }
        if (!TextUtils.isEmpty(images)) {
            images = new StringBuilder(images.substring(0, images.toString().lastIndexOf("||")));
        }
        return images.toString();
    }

    public String CommaSplice() {
        StringBuilder images = new StringBuilder();
        for (PictureBean mDatum : mData) {
            if (mDatum.getItemType() == 1) {
                images.append(mDatum.getNetworkPath()).append(",");
            }
        }
        if (!TextUtils.isEmpty(images)) {
            images = new StringBuilder(images.substring(0, images.toString().lastIndexOf(",")));
        }
        return images.toString();
    }

    public String getCover() {
        return mData.get(0).getCover();
    }


    public int getMaxSelectNum() {
        return maxSelectNum;
    }

    private MyClickListener2 listener;

    public void setMyClickListener(@Nullable MyClickListener2 l) {
        this.listener = l;
    }

    public int getSelectMimeType() {
        return selectMimeType;
    }

    public void setSelectMimeType(int selectMimeType) {
        this.selectMimeType = selectMimeType;
    }

    /**
     * 处理视频缩略图
     */
    public static class MeOnVideoThumbnailEventListener implements OnVideoThumbnailEventListener {

        @Override
        public void onVideoThumbnail(Context context, String videoPath, OnKeyValueResultCallbackListener call) {
            Glide.with(context).asBitmap().sizeMultiplier(0.6F).load(videoPath).into(new CustomTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    resource.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                    FileOutputStream fos = null;
                    String result = null;
                    try {
                        File targetFile = new File(context.getExternalCacheDir().getPath(), "thumbnails_" + System.currentTimeMillis() + ".jpg");
                        fos = new FileOutputStream(targetFile);
                        fos.write(stream.toByteArray());
                        fos.flush();
                        result = targetFile.getAbsolutePath();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        PictureFileUtils.close(fos);
                        PictureFileUtils.close(stream);
                    }
                    if (call != null) {
                        call.onCallback(videoPath, result);
                    }
                }

                @Override
                public void onLoadCleared(@Nullable Drawable placeholder) {
                    if (call != null) {
                        call.onCallback(videoPath, "");
                    }
                }
            });
        }
    }

    public void uploadVideo() {
        isVideo = true;
        MyUtils.fileUpload(activity, new File(destPath), PictureSelectAdapter.this, 0,true);
    }


}
